package org.bingdianleil.config;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class MultiThreadConfig {
	
	private static final Logger logger = LoggerFactory.getLogger(MultiThreadConfig.class);

    @Value("${thread.core_pool_size}")
    private int corePoolSize;
    @Value("${thread.max_pool_size}")
    private int maxPoolSize;
    @Value("${thread.queue_capacity}")
    private int queueCapacity;
    @Value("${thread.name.prefix}")
    private String namePrefix;
    
    
    
	
	@Bean
    public ThreadPoolTaskExecutor defaultThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数目
        executor.setCorePoolSize(corePoolSize);
        //指定最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列中最大的数目
        executor.setQueueCapacity(queueCapacity);
        //线程名称前缀
        executor.setThreadNamePrefix(namePrefix);
        //rejection-policy：当pool已经达到max size的时候，如何处理新任务
        //CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        //对拒绝task的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        //加载
        executor.initialize();
        return executor;
    }
	
	@Bean
    public ScheduledThreadPoolExecutor asyncScheduledThreadPoolExecutor(){

        logger.info("start asyncScheduledThreadPoolExecutor");

        ScheduledThreadPoolExecutor executor=new ScheduledThreadPoolExecutor(10);
        //核心线程数目
        executor.setCorePoolSize(corePoolSize);
        //指定最大线程数
        executor.setMaximumPoolSize(maxPoolSize);
        
        executor.setKeepAliveTime(5, TimeUnit.SECONDS);
         
        return executor;
    }
 
 
}
